<?php

namespace br\com\cf\library\core\connection;

use br\com\cf\library\core\config\Config,
    br\com\cf\Bootstrap

;

/**
 * @author Michael F. Rodrigues <cerberosnash@gmail.com>
 * @version 0.0.0
 */
class Connection
{

    /**
     * @var \PDO
     */
    private static $connection = array();

    /**
     * @return void
     */
    private function __construct ($entry = 'default')
    {
        try {

            $cfg = Config::factory();

            $database = $cfg->getParam("database.{$entry}.database");
            $host = $cfg->getParam("database.{$entry}.host");
            $user = $cfg->getParam("database.{$entry}.user");
            $password = $cfg->getParam("database.{$entry}.password");
            $driver = $cfg->getParam("database.{$entry}.driver");

            self::$connection[$entry] = new \PDO(sprintf("%s:host=%s;dbname=%s", $driver, $host, $database),
                            $user, $password, Bootstrap::factory()->getPDOExtraParams()
            );

            self::$connection[$entry]->setAttribute(
                    \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION
            );
        } catch (\PDOException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * @return \PDO
     */
    public static function factory ($entry)
    {
        return self::singleton($entry);
    }

    /**
     * @return \PDO
     */
    private static function singleton ($entry)
    {
        if (!isset(self::$connection[$entry])) {
            new self($entry);
        }
        return self::$connection[$entry];
    }

}